<?php
/**
 * 用户类
 * 处理用户登录、注册、权限验证等功能
 */

require_once __DIR__ . '/Database.php';

class User {
    private $db;
    private $userId = null;
    private $userData = null;
    
    /**
     * 构造函数
     */
    public function __construct() {
        $this->db = Database::getInstance();
        $this->initSession();
    }
    
    /**
     * 初始化会话
     */
    private function initSession() {
        if (session_status() === PHP_SESSION_NONE) {
            session_start();
        }
        
        // 检查用户是否已登录
        if (isset($_SESSION['user_id'])) {
            $this->userId = $_SESSION['user_id'];
            $this->loadUserData();
        }
    }
    
    /**
     * 加载用户数据
     */
    private function loadUserData() {
        if ($this->userId) {
            $sql = "SELECT * FROM " . DB_PREFIX . "users WHERE id = ?";
            $this->userData = $this->db->fetchRow($sql, [$this->userId]);
        }
    }
    
    /**
     * 用户登录
     * @param string $username 用户名
     * @param string $password 密码
     * @return bool 是否登录成功
     */
    public function login($username, $password) {
        // 查询用户
        $sql = "SELECT * FROM " . DB_PREFIX . "users WHERE username = ? OR email = ?";
        $user = $this->db->fetchRow($sql, [$username, $username]);
        
        // 验证密码
        if ($user && password_verify($password, $user['password'])) {
            // 登录成功，设置会话
            $_SESSION['user_id'] = $user['id'];
            $_SESSION['username'] = $user['username'];
            $_SESSION['role'] = $user['role'];
            
            // 更新最后登录时间
            $this->db->update('users', 
                ['last_login' => date('Y-m-d H:i:s')], 
                'id = ?', 
                [$user['id']]
            );
            
            $this->userId = $user['id'];
            $this->userData = $user;
            
            return true;
        }
        
        return false;
    }
    
    /**
     * 用户注册
     * @param array $userData 用户数据
     * @return int|false 注册成功返回用户ID，失败返回false
     */
    public function register($userData) {
        // 检查用户名是否已存在
        $sql = "SELECT COUNT(*) FROM " . DB_PREFIX . "users WHERE username = ?";
        $usernameExists = $this->db->fetchOne($sql, [$userData['username']]);
        
        if ($usernameExists) {
            return ['success' => false, 'message' => '用户名已存在'];
        }
        
        // 检查邮箱是否已存在
        $sql = "SELECT COUNT(*) FROM " . DB_PREFIX . "users WHERE email = ?";
        $emailExists = $this->db->fetchOne($sql, [$userData['email']]);
        
        if ($emailExists) {
            return ['success' => false, 'message' => '邮箱已被注册'];
        }
        
        // 准备注册数据
        $data = [
            'username' => $userData['username'],
            'email' => $userData['email'],
            'password' => password_hash($userData['password'], PASSWORD_DEFAULT),
            'role' => 'user', // 默认角色
            'created_at' => date('Y-m-d H:i:s'),
            'membership_level' => 'basic', // 默认会员级别
            'is_active' => 1
        ];
        
        // 插入用户记录
        try {
            $userId = $this->db->insert('users', $data);
            
            // 创建默认的用户配置文件
            $profileData = [
                'user_id' => $userId,
                'child_name' => isset($userData['child_name']) ? $userData['child_name'] : '',
                'child_age' => isset($userData['child_age']) ? $userData['child_age'] : 0,
                'created_at' => date('Y-m-d H:i:s')
            ];
            
            $this->db->insert('user_profiles', $profileData);
            
            return ['success' => true, 'user_id' => $userId];
        } catch (PDOException $e) {
            error_log("注册失败: " . $e->getMessage());
            return ['success' => false, 'message' => '注册失败，请稍后重试'];
        }
    }
    
    /**
     * 用户登出
     */
    public function logout() {
        // 清除会话数据
        $_SESSION = [];
        
        // 如果使用了会话cookie，也清除它
        if (ini_get("session.use_cookies")) {
            $params = session_get_cookie_params();
            setcookie(session_name(), '', time() - 42000,
                $params["path"], $params["domain"],
                $params["secure"], $params["httponly"]
            );
        }
        
        // 销毁会话
        session_destroy();
        
        $this->userId = null;
        $this->userData = null;
    }
    
    /**
     * 检查用户是否已登录
     * @return bool 是否已登录
     */
    public function isLoggedIn() {
        return $this->userId !== null;
    }
    
    /**
     * 获取当前用户ID
     * @return int|null 用户ID或null
     */
    public function getUserId() {
        return $this->userId;
    }
    
    /**
     * 获取用户数据
     * @return array|null 用户数据或null
     */
    public function getUserData() {
        return $this->userData;
    }
    
    /**
     * 检查用户是否具有特定角色
     * @param string $role 角色名称
     * @return bool 是否具有该角色
     */
    public function hasRole($role) {
        if (!$this->isLoggedIn()) {
            return false;
        }
        
        return $this->userData['role'] === $role;
    }
    
    /**
     * 检查用户是否是管理员
     * @return bool 是否是管理员
     */
    public function isAdmin() {
        return $this->hasRole('admin');
    }
    
    /**
     * 获取用户会员级别
     * @return string 会员级别
     */
    public function getMembershipLevel() {
        if (!$this->isLoggedIn()) {
            return 'guest';
        }
        
        return $this->userData['membership_level'];
    }
    
    /**
     * 更新用户资料
     * @param array $data 要更新的数据
     * @return bool 是否更新成功
     */
    public function updateProfile($data) {
        if (!$this->isLoggedIn()) {
            return false;
        }
        
        try {
            // 更新用户基本信息
            if (isset($data['email']) || isset($data['username'])) {
                $updateData = [];
                
                if (isset($data['email'])) {
                    $updateData['email'] = $data['email'];
                }
                
                if (isset($data['username'])) {
                    $updateData['username'] = $data['username'];
                }
                
                $this->db->update('users', $updateData, 'id = ?', [$this->userId]);
            }
            
            // 更新用户详细资料
            if (isset($data['child_name']) || isset($data['child_age'])) {
                $profileData = [];
                
                if (isset($data['child_name'])) {
                    $profileData['child_name'] = $data['child_name'];
                }
                
                if (isset($data['child_age'])) {
                    $profileData['child_age'] = $data['child_age'];
                }
                
                // 检查是否存在资料记录
                $sql = "SELECT COUNT(*) FROM " . DB_PREFIX . "user_profiles WHERE user_id = ?";
                $profileExists = $this->db->fetchOne($sql, [$this->userId]);
                
                if ($profileExists) {
                    $this->db->update('user_profiles', $profileData, 'user_id = ?', [$this->userId]);
                } else {
                    $profileData['user_id'] = $this->userId;
                    $profileData['created_at'] = date('Y-m-d H:i:s');
                    $this->db->insert('user_profiles', $profileData);
                }
            }
            
            // 重新加载用户数据
            $this->loadUserData();
            
            return true;
        } catch (PDOException $e) {
            error_log("更新用户资料失败: " . $e->getMessage());
            return false;
        }
    }
    
    /**
     * 更改密码
     * @param string $currentPassword 当前密码
     * @param string $newPassword 新密码
     * @return bool 是否成功
     */
    public function changePassword($currentPassword, $newPassword) {
        if (!$this->isLoggedIn()) {
            return false;
        }
        
        // 验证当前密码
        if (!password_verify($currentPassword, $this->userData['password'])) {
            return false;
        }
        
        // 更新密码
        $data = [
            'password' => password_hash($newPassword, PASSWORD_DEFAULT),
            'updated_at' => date('Y-m-d H:i:s')
        ];
        
        try {
            $this->db->update('users', $data, 'id = ?', [$this->userId]);
            $this->loadUserData(); // 重新加载用户数据
            return true;
        } catch (PDOException $e) {
            error_log("更改密码失败: " . $e->getMessage());
            return false;
        }
    }
} 